package com.cndw.kungfu.ext;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.codehaus.jackson.JsonParser.Feature;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;
import org.codehaus.jackson.map.type.TypeFactory;

/**
 * json封装
 * 
 * @author fantadust Map map = new
 *         ObjectMapper().configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES,
 *         true).readValue("{a:1, b:2}", HashMap.class);
 */
public class JsonProcesser {
	private static final ObjectMapper objectMapper;

	static {
		objectMapper = new ObjectMapper();
		objectMapper.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
		objectMapper.setSerializationConfig(objectMapper.getSerializationConfig().withSerializationInclusion(Inclusion.NON_NULL));
	}

	public static String objectJsonEncode(Object objectSource) throws Exception {

		return objectMapper.writeValueAsString(objectSource);

	}

	public static <T> T objectJsonDecode(String objectSource, Class<T> clazz) throws Exception {

		return objectMapper.readValue(objectSource, clazz);

	}

	public static <K, V> Map<K, V> objectJsonMapDecode(String objectSource, Class<K> keyClass, Class<V> valueClass) throws Exception {
		return objectMapper.readValue(objectSource, TypeFactory.defaultInstance().constructMapType(HashMap.class, keyClass, valueClass));

	}

	public static <T> List<T> objectJsonArrayDecode(String objectSource, Class<T> clazz) throws Exception {

		List<T> list = null;

		list = objectMapper.readValue(objectSource, TypeFactory.defaultInstance().constructCollectionType(List.class, clazz));

		return list;
	}

}
